<template>
  <div class="container">
    <div class="add-text-btn">
      <button type="primary" size="mini" @click="goAddArticle" open-type="getUserInfo">+添加文章</button>
    </div>
    <articleList :articleArr="articleArr" />
  </div>
</template>

<script>
import articleList from '@/components/articleList'
import {requestUrl, wxRequest} from '../../requestApi/request'
export default {
  data () {
    return {
      articleArr: [],
      currPage: 1,
      isFinished: false // 是否全部加载完成
    }
  },
  components: {
    articleList
  },
  methods: {
    getArticle () {
      wxRequest({
        url: requestUrl.getArticle,
        data: {
          currPage: this.currPage
        }
      }).then((result) => {
        const { data } = result
        if (data.code === 200) {
          if (data.message.length > 0) {
            this.currPage++
            this.articleArr = this.articleArr.concat(data.message)
          } else {
            this.isFinished = true
            wx.showToast({
              title: '已无更多',
              icon: 'none',
              duration: 1500,
              mask: false
            })
          }
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    goAddArticle () {
      // 获取当前用户信息
      wx.getUserInfo({
        success (result) {
          wx.setStorageSync('userInfo', result.userInfo)
        }
      })
      wx.navigateTo({
        url: '/pages/articleAdd/main'
      })
    },
    initData () {
      this.currPage = 1
      this.articleArr = []
      this.isFinished = false
    }
  },
  onShow () {
    // created在小程序中只会执行一次，所以这里使用onShow
    this.initData()
    this.getArticle()
  },
  // 上拉加载
  onReachBottom () {
    if (!this.isFinished) {
      // 上拉加载
      wx.showLoading({
        title: '加载中...',
        success: () => {
          this.getArticle()
        }
      })
      setTimeout(() => {
        wx.hideLoading()
      }, 1000)
    }
  },
  // 下拉刷新
  onPullDownRefresh () {
    this.initData()
    wx.showLoading({
      title: '刷新中...',
      success: () => {
        this.getArticle()
      }
    })
    setTimeout(() => {
      wx.hideLoading()
      wx.stopPullDownRefresh()
    }, 1000)
  }
}
</script>

<style scoped>
.container {
  height: 100%;
  padding: 20rpx;
  box-sizing: border-box;
}
.add-text-btn {
  text-align: right;
  position: fixed;
  top: 0;
  right: 20rpx;
  width: 100%;
  background-color: #fff;
}
</style>
